package com.situ.crm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.crm.entity.Role;
import com.situ.crm.entity.RoleMenu;
import com.situ.crm.entity.UserRole;
import com.situ.crm.mapper.RoleMapper;
import com.situ.crm.mapper.RoleMenuMapper;
import com.situ.crm.mapper.UserRoleMapper;
import com.situ.crm.service.IRoleService;
import com.situ.crm.vo.ResultDataVO;

@Service("roleService")
public class RoleServiceImpl implements IRoleService {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	@Autowired
	private RoleMenuMapper roleMenuMapper;

	@Override
	public ResultDataVO selectRoleList(String name, Integer page, Integer limit) {
		ResultDataVO result = new ResultDataVO();
		PageHelper.startPage(page, limit);
		List<Role> list = roleMapper.selectRoles(name);
		result.setData(list);
		PageInfo<Role> pageInfo = new PageInfo<>(list);
		result.setCount(pageInfo.getTotal());
		return result;
	}

	@Override
	public void save(Role role) {
		if (role.getId() == null) {
			roleMapper.insert(role);
		} else {
			roleMapper.updateByPrimaryKey(role);
		}
	}

	@Override
	public Role selectRoleById(Integer id) {
		return roleMapper.selectByPrimaryKey(id);
	}

	@Override
	public void delRole(Integer id) {
		roleMapper.deleteByPrimaryKey(id);
	}

	@Override
	public List<Role> selectAllRole(Integer userId) {
		// 系统中的所有角色
		List<Role> list = roleMapper.selectAll();
		// 用户已经有了哪些角色
		List<UserRole> userRoleList = userRoleMapper.selectByUserId(userId);
		for (Role role : list) {// 遍历所有的角色
			for (UserRole userRole : userRoleList) {
				if (role.getId().equals(userRole.getRoleId())) {
					role.setChecked("1");
				}
			}
		}
		return list;
	}

	@Override
	public void saveMenu(Integer roleId, Integer[] ids) {

		roleMenuMapper.deleteByRoleId(roleId);
		
		// 遍历所有的菜单ID
		for (Integer menuId : ids) {
			roleMenuMapper.insert(new RoleMenu(roleId, menuId));
		}

	}

}
